package com.sniper.web.action.error;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sniper.utils.HttpRequestUtils;
import com.sniper.web.action.RootController;
import com.sniper.web.utils.ControllerUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 设置设置shrio的非法访问显示页面
 *
 * @author suzhen
 */
@ControllerAdvice
public class ErrorController extends RootController {
    /**
     * 异常优先级，里错误越近，越优先被打印出 方法不能传入map，如果把异常信息传到页面上，需要使用modelAndView
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = AuthorizationException.class)
    public ModelAndView NuAccess(Exception ex) {
        baseHref.setBaseHref(getBasePath());
        ModelAndView mv = new ModelAndView("/error/UnAccess.jsp");
        mv.addObject("baseHref", baseHref);
        mv.addObject("ex", ex);
        return mv;
    }

    @ExceptionHandler(value = NullPointerException.class)
    public Object NullPointer(Exception ex, HttpServletResponse response) throws IOException {

        //输出错误
        StackTraceElement[] stackTrace = ex.getStackTrace();
        for (StackTraceElement element : stackTrace) {
            LOGGER.error(element.toString());
        }
        if (HttpRequestUtils.isAjax(request)) {
            ControllerUtils.CallBackResult callBackResult = new ControllerUtils.CallBackResult();
            callBackResult.setMsg(ex.getMessage());
            PrintWriter printWriter = response.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            printWriter.write(mapper.writeValueAsString(callBackResult));
            printWriter.flush();
            return null;
        }

        baseHref.setBaseHref(getBasePath());
        ModelAndView mv = new ModelAndView("/error/admin-404.jsp");
        mv.addObject("baseHref", baseHref);
        mv.addObject("ex", ex);
        return mv;
    }


//    @ExceptionHandler(value = {ExecutionException.class, InterruptedException.class})
//    public ModelAndView forkSolr(Exception ex) {
//        baseHref.setBaseHref(getBasePath());
//        ModelAndView mv = new ModelAndView("/error/500.jsp");
//        mv.addObject("baseHref", baseHref);
//        mv.addObject("ex", ex);
//        return mv;
//    }

}
